<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <p mv-text="name"></p>
    <p mv-text="name"></p>
    <h3 mv-text="age"></h3>
    <h3 mv-text="age"></h3>
  </div>
  <script>
    let Watcher = function () {

    }
    Watcher.prototype.notify = function (key, nv) {
      for (let i = 0; i < this[key].length; i++) {
        this[key][i].textContent = nv //取值操作触发get()
      }

    }
    // 构造函数
    let Mvvm = function (options) {
      // this是Mvvm的当前实例
      this.$el = document.querySelector(options.el)
      this._data = options.data
      let subsDom = new Watcher()
      Object.keys(this._data).forEach(key => {
        // css属性选择器
        let selStr = `[mv-text="${key}"]`
        subsDom[key] = this.$el.querySelectorAll(selStr) //数组集合
      })
      // console.log()
      // 把data中的所有值都通过数据劫持绑定到当前this实例
      Object.keys(this._data).forEach(key => {
       subsDom.notify(key,this._data[key])

        Object.defineProperty(this, key, {
          get() {
            console.log('get')
            return this._data[key]
          },
          set(nv) {
            // this当前vm实例
            this._data[key] = nv
            subsDom.notify(key,this._data[key])
          }
        })
      })
    }
    let mv = new Mvvm({
      el: "#app",
      data: {
        name: 'zs',
        age: 10
      }

    })

  </script>
</body>

</html>